﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WpfApp.Models;
using WpfApp.Views;

namespace WpfApp.ViewModels
{
    class HomePageViewModel: NotificationObject
    {
		private string user;
		private Word? showWord;

		public Word ShowWord
		{
			get { return showWord; }
			set
			{
				showWord = value;
				this.RaisePropertyChanged("ShowWord");
            }
		}
 
        private string? searchWord;

		public string? SearchWord
		{
			get { return searchWord; }
			set
			{
				searchWord = value;
				this.RaisePropertyChanged("SearchWord");
			}
		}
		private string myWord;

		public string MyWord
		{
			get { return myWord; }
			set
			{
				myWord = value;
				this.RaisePropertyChanged("MyWord");
			}
		}


		public ObservableCollection<Word>? History { set; get; }
		//网络搜索

        public DelegateCommand? SearchCommand { get; set; }
		//拍照识别

        public DelegateCommand? PhotoSearchCommand { get; set; }
		//加入生词本

        public DelegateCommand? AddCommand { get; set; }
		//显示
		public DelegateCommand? DisplayCommand { get; set; }


		//拍照上传

		public void photoSearch(Object obj)
		{
            OpenFileDialog openFileDialog = new OpenFileDialog();
            // 显示对话框并检查用户是否选择了文件
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取选中的文件路径
                string selectedFilePath = openFileDialog.FileName;

                OcrProcessor ocrProcessor = new OcrProcessor();
				SearchWord	 = ocrProcessor.ExtractTextFromImage(selectedFilePath)[0];
            }
        }
        
        public async void search(Object obj)
		{

			ShowWord = new Word { Name = searchWord, Meaning = await ProTrans.GetProTrans(SearchWord) };
			History.Insert(0, ShowWord);
            MainWindow.data.AddWord(MainMenu.userName, "历史查询", ShowWord);
            MyWord = "加入生词本";
		}

		public void AddToMyWord(Object obj)
		{
			if (MyWord == "已加入") return;
			//加入生词本操作
			MainWindow.data.AddWord(MainMenu.userName, "我的生词本", ShowWord);
			MyWord = "已加入";
        } 

		public void display(Object word)
		{
			ShowWord = (Word)word;
            MyWord = "加入生词本";
        }

		public HomePageViewModel(string user)
		{
			History = new ObservableCollection<Word>(MainWindow.data.GetWords(MainMenu.userName, "历史查询"));
			MyWord = "加入生词本";
			PhotoSearchCommand = new DelegateCommand();
			PhotoSearchCommand.ExecuteAction += new Action<object>(this.photoSearch);
			SearchCommand = new DelegateCommand();
			SearchCommand.ExecuteAction += new Action<object>(this.search);
			AddCommand = new DelegateCommand();
			AddCommand.ExecuteAction += new Action<object>(this.AddToMyWord);
			DisplayCommand = new DelegateCommand();
			DisplayCommand.ExecuteAction += new Action<object>(this.display);
		}
    }
}
